package com.qf.wangqing.sportsnews.fragment;


import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.util.Pair;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.exoplayer.metadata.id3.BinaryFrame;
import com.qf.wangqing.sportsnews.BR;
import com.qf.wangqing.sportsnews.MyApplication;
import com.qf.wangqing.sportsnews.R;
import com.qf.wangqing.sportsnews.adapter.recommendadapter.RDCommentRecyclerAdapter;
import com.qf.wangqing.sportsnews.bean.RecommendBannersEntity;
import com.qf.wangqing.sportsnews.bean.RecommendBannersExtraEntity;
import com.qf.wangqing.sportsnews.bean.RecommendContentsEntity;
import com.qf.wangqing.sportsnews.bean.RecommendContestEntity;
import com.qf.wangqing.sportsnews.bean.RecommendContestListEntity;
import com.qf.wangqing.sportsnews.bean.RecommendContestListExtraEntity;
import com.qf.wangqing.sportsnews.bean.RecommendDataEntity;
import com.qf.wangqing.sportsnews.bean.RecommendRootEntity;
import com.qf.wangqing.sportsnews.bean.RecommendTopsEntity;
import com.qf.wangqing.sportsnews.databinding.FragmentNewsBaseBinding;
import com.qf.wangqing.sportsnews.databinding.RbGuessItemBinding;
import com.qf.wangqing.sportsnews.utils.DividerItemDecoration;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import in.srain.cube.views.ptr.PtrDefaultHandler;
import in.srain.cube.views.ptr.PtrFrameLayout;
import in.srain.cube.views.ptr.PtrHandler;
import in.srain.cube.views.ptr.PtrUIHandler;
import in.srain.cube.views.ptr.header.StoreHouseHeader;
import in.srain.cube.views.ptr.indicator.PtrIndicator;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;


/**
 * A simple {@link Fragment} subclass.
 */
public class NewsBaseFragment extends Fragment implements Callback<RecommendRootEntity>, PtrHandler {


    private FragmentNewsBaseBinding binding;
    private RDCommentRecyclerAdapter rdCommentRecyclerAdapter;
    private Map<Class<?>,Pair<Integer,Integer>> map;
    private int channelId;
    private ImageView arrow;
    private TextView refresh;
    private TextView refreshTime;
    private MyApplication myApplication;
    private long startId = -1;
    private boolean loading = false;

    public NewsBaseFragment() {
        // Required empty public constructor
    }

    public static NewsBaseFragment newInstance(int type) {

        Bundle args = new Bundle();
        args.putInt("type",type);
        NewsBaseFragment fragment = new NewsBaseFragment();
        fragment.setArguments(args);
        return fragment;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        binding = DataBindingUtil.inflate(LayoutInflater.from(getContext()), R.layout.fragment_news_base,container,false);
        return binding.getRoot();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        init();
        myApplication = (MyApplication) getActivity().getApplication();
//        myApplication.getNewsService().getRecommendData().enqueue(this);
        //传的id
       channelId=getArguments().getInt("type");
        myApplication.getNewsService().getRecommendRoot(channelId,"json","4","false",new HashMap<String, String>()).enqueue(this);
    }
    private void init(){
        map = new HashMap<>();
        map.put(RecommendBannersExtraEntity.class, Pair.create(R.layout.rd_focus_images, BR.images));
        map.put(RecommendTopsEntity.class,Pair.create(R.layout.topitem_long,BR.tops));
        map.put(RecommendContentsEntity.class,Pair.create(R.layout.contentitem_long,BR.contents));
        //竞猜
        map.put(RecommendContestListExtraEntity.class,Pair.create(R.layout.rd_guess_items,BR.list));

        rdCommentRecyclerAdapter = new RDCommentRecyclerAdapter<>(getActivity(), new ArrayList(), map);
        binding.recycler.setAdapter(rdCommentRecyclerAdapter);
        binding.recycler.addItemDecoration(new DividerItemDecoration(getContext(),DividerItemDecoration.VERTICAL_LIST));
        //下拉刷新的操作
//        StoreHouseHeader header = new StoreHouseHeader(getContext());
//        header.initWithString("load....");
//        binding.ptr.addPtrUIHandler(header);
//        binding.ptr.setHeaderView(header);
        View header = LayoutInflater.from(getContext()).inflate(R.layout.ptr, null);
        binding.ptr.setHeaderView(header);
        binding.ptr.setPtrHandler(this);
        arrow = (ImageView) header.findViewById(R.id.arrow);
        refresh = (TextView) header.findViewById(R.id.refresh);
        refreshTime = (TextView) header.findViewById(R.id.refreshTime);
        binding.ptr.addPtrUIHandler(new PtrUIHandler() {
            @Override
            public void onUIReset(PtrFrameLayout frame) {
                ViewCompat.setRotation(arrow,0);
                ViewCompat.animate(arrow).cancel();
                refresh.setText("下拉刷新");
                arrow.setBackgroundResource(R.mipmap.xlistview_arrow);
                isRotate = false;
            }

            @Override
            public void onUIRefreshPrepare(PtrFrameLayout frame) {

            }

            @Override
            public void onUIRefreshBegin(PtrFrameLayout frame) {
//                ViewCompat.animate(arrow)
//                        .rotationBy(-180)
//                        .setDuration(100)
//                        .start();
//                refresh.setText("松开刷新数据");
                arrow.setBackgroundResource(R.mipmap.loading_img);
                refresh.setText("正在加载");
                ViewCompat.animate(arrow)
                        .rotationBy(36000)
                        .setDuration(120000)
                        .start();
            }

            @Override
            public void onUIRefreshComplete(PtrFrameLayout frame) {

            }
            private boolean isRotate = false;
            @Override
            public void onUIPositionChange(PtrFrameLayout frame, boolean isUnderTouch, byte status, PtrIndicator ptrIndicator) {
                int currentPosY = ptrIndicator.getCurrentPosY();
                int headerHeight = binding.ptr.getHeaderHeight();
                if ( !isRotate && currentPosY > headerHeight) {
                    refresh.setText("松开刷新数据");
                    ViewCompat.animate(arrow)
                        .rotationBy(-180)
                        .setDuration(100)
                        .start();
                    isRotate = true;
                }

            }
        });

        //滚动监听
        binding.recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                //判断是否快到底部
                //获取可显示的最后一个view
                View item = recyclerView.getChildAt(recyclerView.getChildCount() - 1);
               //最后一个item的位置
                int position = recyclerView.getChildAdapterPosition(item);
                //小于5表示快接近底部
                if (!loading && position > rdCommentRecyclerAdapter.getItemCount()-5) {
                    HashMap<String, String> map = new HashMap<>();
                    map.put("start_id",String.valueOf(startId));
                    loading = true;
                    myApplication.getNewsService().getRecommendRoot(channelId,"json","4","false",map).enqueue(NewsBaseFragment.this);
                }

            }
        });
    }


    @Override
    public void onResponse(Call<RecommendRootEntity> call, Response<RecommendRootEntity> response) {
        if (startId == -1) {
            rdCommentRecyclerAdapter.clear();
        }

        RecommendRootEntity body = response.body();
        List<RecommendContentsEntity> contents = body.getData().getContents();
        startId = contents.get(contents.size()-1).getId();
        RecommendBannersExtraEntity bannersExtraEntity = new RecommendBannersExtraEntity(body.getData().getBanners());
       RecommendContestListExtraEntity contestListExtraEntity = new RecommendContestListExtraEntity(body.getData().getContest_list());
        if (bannersExtraEntity.getBanners() != null && bannersExtraEntity.getBanners().size() !=0 ) {
            rdCommentRecyclerAdapter.add(0, bannersExtraEntity);
        }
        //竞猜的数据
        if (channelId == 0) {
            if (contestListExtraEntity.getContest_list() != null && contestListExtraEntity.getContest_list().size() != 0) {
                rdCommentRecyclerAdapter.add(1, contestListExtraEntity);
            }
        }

        if (body.getData().getTops() !=null && body.getData().getTops().size() != 0) {
            rdCommentRecyclerAdapter.addAll(body.getData().getTops());
        }
        if (body.getData().getContents() != null && body.getData().getContents().size() != 0) {
            rdCommentRecyclerAdapter.addAll(body.getData().getContents());
        }
        binding.ptr.refreshComplete();
        loading = false;
    }

    @Override
    public void onFailure(Call<RecommendRootEntity> call, Throwable t) {
            t.printStackTrace();
        Toast.makeText(getContext(), t.getMessage(), Toast.LENGTH_SHORT).show();
        binding.ptr.refreshComplete();
        loading = false;
    }

    @Override
    public boolean checkCanDoRefresh(PtrFrameLayout frame, View content, View header) {
        return PtrDefaultHandler.checkContentCanBePulledDown(frame, content, header);
    }

    @Override
    public void onRefreshBegin(PtrFrameLayout frame) {
        startId = -1;
        myApplication.getNewsService().getRecommendRoot(channelId,"json","4","false",new HashMap<String, String>()).enqueue(this);

    }
}
